package com.yanhao.act.fragment.project

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.fragment.app.viewModels
import com.yanhao.databinding.FragmentProjectBinding
import com.yanhao.viewmode.ProjectViewModel
import com.yanhao.viewmode.ProjectViewModelFactory


class ProjectFragment : Fragment() {

    private var _binding: FragmentProjectBinding? = null
    private val binding get() = _binding!!

    private val vm by viewModels<ProjectViewModel> {
        ProjectViewModelFactory()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        arguments?.let {
//            param1 = it.getString(ARG_PARAM1)
//            param2 = it.getString(ARG_PARAM2)
//        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentProjectBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        vm.projectTreeTitle.observe(viewLifecycleOwner) {
            val fragments = mutableListOf<Fragment>()
            val titles = mutableListOf<String>()
            it.forEach { projectTitle ->
                titles.add(projectTitle.name)
                binding.tablayout.addTab(binding.tablayout.newTab().setText(projectTitle.name))
                fragments.add(
                    ProjectInfoFragment.newInstance(
                        param1 = projectTitle.name,
                        param2 = projectTitle.id
                    )
                )
            }
//                binding.viewpager.offscreenPageLimit = 0
            binding.viewpager.adapter = object : FragmentStatePagerAdapter(
                childFragmentManager,
                BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
            ) {
                override fun getCount(): Int = fragments.size

                override fun getItem(position: Int): Fragment = fragments[position]

                override fun getPageTitle(position: Int): CharSequence = titles[position]

            }
            binding.tablayout.setupWithViewPager(binding.viewpager, false)
        }
        vm.getProjectTabTitle()
    }

    companion object {
        @JvmStatic
        fun newInstance() = ProjectFragment()
    }
}